/**
 * This class stores list of Orders
 * @author Sayatbek
 *
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class OrderList{
        private ArrayList <Order> orderList;
        public OrderList(){
                orderList = new ArrayList<Order>();
        }
        
        /** 
    	 * Finds the sdmCompetitor of the list when given a number
    	 * @param number integer of the competitor number 
    	 */
    	public Order findById(String id){
    		//Loops through all competitors looking for given id number
    		id = id.trim();
    		int number = Integer.parseInt(id);
    		for (Order o : orderList){
    			if (Integer.parseInt(o.getId().trim()) == number){
    				//if number is found in list return that competitor
    				return o; 
    			}
    		}
    		//if not return null
    		return null;
    	}
    	/**
    	 * 
    	 * @param id
    	 * @return report
    	 */
    	
    	public String getReceiptById(String id){
    		Order o = findById(id);
    		String report = "ID CustomerId	ItemId	PriceOfProduct	Quantity  OverAllCost\n"; 
        	report += String.format("%-4s", ""+o.getId());
			report += String.format("%-13s", o.getCustomerId());
			//report += String.format("%-13s", o.getPriceOfProduct());
			report += String.format("%-8.3s", o.getItemId());
			report += String.format("%-10s",o.getQuantity());
			//report += String.format("%-13s",o.getOverallCost());
			report += "\n";
    		return report;
    	}
    	
        /** 
    	 * Adds an order to the array of orders
    	 * @param  order as an Order class object
    	 * @return boolean value, true if element is added
    	 */
    	public boolean addOrder(Order order){
    		String id = order.getId();
    		Order inList = this.findById(id);
    		//Finds the number of the given competitor, should 
    		//that element not already exist in the list it is added
    		if (inList == null){
    			orderList.add(order);
    			return true;
    		}
    		return false;
    	}
    	
        /**
         * 
         */
        public void sortOrders(){
        	
        }
        
        /**
         * 
         * @param filename
         */
        public void readFile(String filename) {
    		String inputLine = "";
    		try {
    			File f = new File(filename);
    			Scanner scanner = new Scanner(f);
    			if (scanner.hasNextLine()){
    				inputLine = scanner.nextLine();
    			}
    			while (scanner.hasNextLine()) {
    				//loop while is another line to be read
    				inputLine = scanner.nextLine();		
    				ProcessLine(inputLine);
    			}
    		}
    		catch (FileNotFoundException fnf){
    			System.out.println("Error in CompetitorList.readFile "+ filename + " not found.");
    			System.exit(0);
    		}
        }
        /**
    	 * Processes line, extracts data, creates SOKCompetitor object
    	 * and adds to list
    	 * Checks for non-numeric items when needed
    	 * @param line the line to be processed
    	 */
    	private void ProcessLine(String line) {
    		try {
    			String parts [] = line.split(",");//create array of String splitting line by comma
    			for(int i=0;i<parts.length;i++){
    				parts[i]=parts[i].trim();//delete extra spaces using trim
    			}
    			
    			String id = parts[0];
    			String customerId = parts[1];
    			String itemId = parts[2];
    			int quantity = Integer.parseInt(parts[3]);
    			double totalCost = Double.parseDouble(parts[4]);
    			double discount = Double.parseDouble(parts[5]);
    			double overallCost = Double.parseDouble(parts[6]);
    			
    			Order order = new Order(id, customerId, itemId, quantity,
    					totalCost, discount, overallCost);
    			this.addOrder(order);
    		}
    		
    		/**
    		 * this catches trying to convert a String to an integer
    		 */
    		catch (NumberFormatException nfe) {
    			String error = "Number conversion error in '" + line + "'  - " 
    			                  + nfe.getMessage();
    			System.out.println(error);
    		}
    		/**
    		 * this catches missing items if only one or two items
    		 *other omissions will result in other errors
    		 */
    		catch (ArrayIndexOutOfBoundsException air) {
    			String error = "Error - Not enough items in  : '" + line
    			                        + "' index position : " + air.getMessage();
    			System.out.println(error);
    		}
    	}
    	
    	public String getListOfAllOrders(ProductList allProducts){
    		String report = "ID CustomerId	ItemId	Quantity  OverAllCost\n";
    		for (Order o  : orderList){
    			report += String.format("%-4s", ""+o.getId());
    			report += String.format("%-13s", o.getCustomerId());
    			report += String.format("%-8.3s", o.getItemId());
    			report += String.format("%-10s",o.getQuantity());
    			Product p = allProducts.findByID(o.getItemId());
    			
    			double price=0;
    			int Cases = o.getQuantity() / 6;
    			int Units = o.getQuantity() % 6;
    			price += Cases * p.getCasePrice();
    			price += Units * p.getUnitPrice();
    			
    			report += String.format("%-13s",o.getOverallCost(price));
    			report += "\n";
    		}
    		return report;
    	}
    	/** 
    	 * Writes the list of all orders with calculated overallCost to an external text file
    	 * @param fileName string name of the file to be written to
    	 * @param text the string that will be written to the file
    	 */
    	public void writeTo(String fileName, String text) {
    		FileWriter filewriter;
    		try {
    			filewriter = new FileWriter(fileName);
    			filewriter.write("LIST OF ALL ORDERS:\n");
    			filewriter.write("\n");
    			filewriter.write(text);
    			filewriter.close();
    		}
    		//Catch error case where the file name is not found in location
    		catch (FileNotFoundException fnf){
    			System.out.println(fileName + " not found ");
    			System.exit(0);
    		}
    		//Catch the IOException error
    		catch (IOException ioe){
    			ioe.printStackTrace();
    			System.exit(1);
    		}
    	}
    	
}